// AI服务封装 - 基于DeepSeek API
import { ElMessage } from 'element-plus';

class AIService {
  constructor() {
    this.apiKey = process.env.VUE_APP_DEEPSEEK_API_KEY;
    this.baseURL = 'https://api.deepseek.com/chat/completions';
    this.isStoppedByUser = false;
    this.aiStreamReader = null;
  }

  /**
   * 调用AI API（流式响应）
   * @param {Array} messages 对话消息
   * @param {Object} options 配置选项
   * @returns {Promise<string>} AI响应内容
   */
  async callAIStream(messages, options = {}) {
    const {
      model = 'deepseek-chat',
      max_tokens = 1024,
      temperature = 0.1,
      onChunk = null,
      onComplete = null
    } = options;

    this.isStoppedByUser = false;

    try {
      const response = await fetch(this.baseURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          messages,
          model,
          max_tokens,
          temperature,
          stream: true
        })
      });

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
      }

      if (!response.body) {
        throw new Error('服务器未返回流数据');
      }

      const reader = response.body.getReader();
      this.aiStreamReader = reader;
      const decoder = new TextDecoder('utf-8');
      let buffer = '';
      let fullContent = '';

      while (true) {
        if (this.isStoppedByUser) {
          await reader.cancel();
          break;
        }

        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;

        const lines = buffer.split('\n');
        buffer = lines.pop();

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const jsonStr = line.slice(6).trim();
            if (jsonStr === '[DONE]') {
              if (onComplete) onComplete(fullContent);
              return fullContent;
            }

            try {
              const jsonData = JSON.parse(jsonStr);
              const content = jsonData?.choices[0]?.delta?.content || '';

              if (content) {
                fullContent += content;
                if (onChunk) onChunk(content, fullContent);
              }
            } catch (error) {
              console.error('解析JSON数据失败:', error, line);
            }
          }
        }
      }

      return fullContent;
    } catch (error) {
      console.error('AI API调用失败:', error);
      throw error;
    } finally {
      this.aiStreamReader = null;
    }
  }

  /**
   * 停止流式输出
   */
  stopStream() {
    this.isStoppedByUser = true;
    if (this.aiStreamReader) {
      this.aiStreamReader.cancel();
    }
  }

  /**
   * 构建医疗诊断系统提示词
   */
  getMedicalSystemPrompt() {
    return {
      role: 'system',
      content: `你是一个专业的医疗AI助手，专门帮助医生进行诊断分析。请基于患者的症状、体征和检查结果提供专业的医学建议。

      回答要求：
      1. 用中文回答，语言简洁专业。      
      2. 输出内容不要包含特殊字符。`
    };
  }

  /**
   * 通用AI调用方法（非流式）
   */
  async callAISimple(messages, options = {}) {
    const {
      model = 'deepseek-chat',
      max_tokens = 1024,
      temperature = 0.1
    } = options;

    try {
      const response = await fetch(this.baseURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          messages,
          model,
          max_tokens,
          temperature,
          stream: false
        })
      });

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      return data.choices[0].message.content;
    } catch (error) {
      console.error('AI API调用失败:', error);
      throw error;
    }
  }
}

// 创建单例实例
const aiService = new AIService();

export default aiService;